package br.com.abril.pce.service.impl;

import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import br.com.abril.pce.model.Cota;
import br.com.abril.pce.repository.CotaRepository;

@ContextConfiguration(
		locations = { "classpath:/applicationContext.xml" })
@TransactionConfiguration(
		transactionManager = "transactionManager",
		defaultRollback = true)
public class ImportacaoServiceImplTest extends AbstractTransactionalJUnit4SpringContextTests {

	@Autowired
	protected ImportacaoServiceImpl importacaoService;

	@Before
	public void setUp() {

		importacaoService.diretorioEntradaDivida = "src/test/arquivos";
		importacaoService.cotaRepository = mock(CotaRepository.class);

	}

	@Test
	@Transactional
	@DirtiesContext
	public void deveImportarDoisRegistros() throws IOException {

		importacaoService.importaDivida();

		verify(importacaoService.cotaRepository, times(2)).save(any(Cota.class));

		// cleanup

		File diretorioEntrada = new File(importacaoService.diretorioEntradaDivida);
		File arquivoEntrada = new File(diretorioEntrada, "DIVIDA.TXT");

		for (int i = 0; i < diretorioEntrada.listFiles().length; i++) {
			File file = diretorioEntrada.listFiles()[i];
			if (file.getName().startsWith("DIVIDA")) {
				FileUtils.moveFile(file, arquivoEntrada);
			}
		}
	}
}
